package com.corner.presenter.imp;

import com.corner.model.cornerservice.domain.Attention;
import com.corner.model.cornerservice.domain.User;
import com.corner.model.cornerservice.helper.AttentionHelper;
import com.corner.presenter.IAttentionPresenter;
import com.corner.presenter.base.BasePresenter;
import com.corner.ui.view.IAttentionView;

import java.util.List;

import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;

/**
 * Created by Administrator on 2015/7/25，11.16.
 * 描述：
 */
public class AttentionPresenter extends BasePresenter<IAttentionView> implements IAttentionPresenter {

    private boolean hasMore;
    private boolean isLoading;
    private List<Attention> attentions;

    @Override
    public void requestAttention() {
        if (isLoading) {
            return;
        }
        isLoading = true;
        AttentionHelper.getAttentions(User.getCurrentUser().getObjectId(), 0).observeOn(AndroidSchedulers.mainThread()).subscribe(new Action1<List<Attention>>() {
            @Override
            public void call(List<Attention> attentions) {
                if (attentions != null && view != null) {
                    AttentionPresenter.this.attentions = attentions;
                    view.showRequestAttention(attentions);
                    view.requestComplete();
                    hasMore = attentions.size() >= 10;
                    view.setLoadMoreEnable(hasMore);
                }
                isLoading = false;
            }
        }, new Action1<Throwable>() {
            @Override
            public void call(Throwable throwable) {
                if (view != null) {
                    view.requestComplete();
                }
                isLoading = false;
            }
        });
    }

    @Override
    public void loadMoreAttention() {
        if (isLoading || !hasMore) {
            return;
        }
        isLoading = true;
        AttentionHelper.getAttentions(User.getCurrentUser().getObjectId(), 0).observeOn(AndroidSchedulers.mainThread()).subscribe(new Action1<List<Attention>>() {
            @Override
            public void call(List<Attention> attentions) {
                if (attentions != null && view != null) {
                    view.loadMoreComplete();
                    hasMore = attentions.size() >= 10;
                    attentions.addAll(0, AttentionPresenter.this.attentions);
                    view.showLoadMoreAttention(attentions);
                    AttentionPresenter.this.attentions = attentions;
                    view.setLoadMoreEnable(hasMore);
                    isLoading = false;
                }
            }
        }, new Action1<Throwable>() {
            @Override
            public void call(Throwable throwable) {
                if (view != null) {
                    view.loadMoreComplete();
                }
                isLoading = false;
            }
        });
    }
}
